<?php

namespace App\Service\Wanggui;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\FeishuMini\SandTableEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\CityResidencePriceModel;
use App\Models\Common\CityTerritorialBoundaryModel;
use App\Models\Common\ConfigModel;
use App\Models\Common\MapNationalBrandShopModel;
use App\Models\Common\MapNationalCommunityModel;
use App\Models\Common\MapNationalIndustrialParkModel;
use App\Models\Common\MapNationalStreetModel;
use App\Models\Common\MapNationalUniversitiesModel;
use App\Models\Common\MapTownshipPlanAreaModel;
use App\Models\Common\ResourcesModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Guanyuan\GuanyuanSyncShopBusinessModel;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\WaiMai\WaiMaiAnalysisModel;
use App\Models\Wanggui\BusinessAoiModel;
use App\Service\BaseService;
use App\Service\Common\HeatMapService;
use App\Service\OpenShop\Feishu\MapService;
use App\Service\OpenShop\FeishuMini\SandTableService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use App\Service\OpenShop\SiteLocation\SiteLocationService;
use App\Service\WaiMai\WaiMaiAnalysisBuildService;
use App\Service\WaiMai\WaiMaiAnalysisService;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;
use Overtrue\Pinyin\Pinyin;

class WangguiDotService extends BaseService
{

    /**
     * 点位外卖预估
     * @param $lng
     * @param $lat
     * @param $wgNumber
     * @return array[]
     * @throws \Exception
     */
    public static function takeawayEstimate($lng, $lat, $wgNumber): array
    {
        $distance = 3;  //默认3km
        $heatmap  = '';
        // 外卖预估数据

        $takeOutData = (new WaiMaiAnalysisService())
            ->setLngLat($lng, $lat, $distance);

        $estimate = $takeOutData->calcEstimateData();

        $takeOutDoubleSalesVolume         = (int)(array_sum($estimate['estimate']) * 0.8) . '~' . (int)(array_sum($estimate['estimate']) * 1.2);
        $takeOutDoubleSalesVolumeReceived = ((int)(array_sum($estimate['estimate']) * 0.8) * 30) . '~' . ((int)(array_sum($estimate['estimate']) * 1.2) * 30);
        $mtSalesVolume                    = (int)($estimate['estimate']['mt'] * 0.8) . '~' . (int)($estimate['estimate']['mt'] * 1.2);
        $elmSalesVolume                   = (int)($estimate['estimate']['elm'] * 0.8) . '~' . (int)($estimate['estimate']['elm'] * 1.2);

        // 夸父门店TOP3
        $kfSalesVolume = collect($takeOutData->getNearByKfShops(3))->map(function ($item) {
            return [
                'shopName' => $item->shopName,
                'distance' => round($item->distance, 2) . 'km',
                'mtElm'    => $item->mt . ' / ' . $item->elm . ' / ' . ($item->mt + $item->elm),
            ];
        })->values()->toArray();

        // 炸串炸鸡美团TOP5
        $mtFriedGoods = $takeOutData->getNearBySourceTypeRank(RmsShopApi::SOURCE_TYPE_WM_MT, WaiMaiAnalysisModel::CATEGORY_TYPE_FRIED, false, 5)->map(function ($item) {
            return [
                'shopName' => $item['shopName'],
                'distance' => round($item['distance'], 2) . 'km',
                'mt'       => $item['orderNum'],
            ];
        })->values()->toArray();

        if (count($mtFriedGoods)) {
            $mtFriedGoods[] = [
                'shopName' => '平均单量',
                'distance' => '',
                'mt'       => (int)collect($mtFriedGoods)->avg('mt'),
            ];
        }


        // 炸串炸鸡饿了么TOP5
        $elmFriedGoods = $takeOutData->getNearBySourceTypeRank(RmsShopApi::SOURCE_TYPE_WM_ELM, WaiMaiAnalysisModel::CATEGORY_TYPE_FRIED, false, 5)->map(function ($item) {
            return [
                'shopName' => $item['shopName'],
                'distance' => round($item['distance'], 2) . 'km',
                'elm'      => $item['orderNum'],
            ];
        })->values()->toArray();

        if (count($elmFriedGoods)) {
            $elmFriedGoods[] = [
                'shopName' => '平均单量',
                'distance' => '',
                'elm'      => (int)collect($elmFriedGoods)->avg('elm'),
            ];
        }

        //        //地图图片
        //        $image = OpenShopUploadFileResourceModel::query()
        //            ->where('orderNo', $wgNumber)
        //            ->whereIn('position', [UploadFileResourceEnum::TAKE_OUT_HEATMAP, UploadFileResourceEnum::CLUE_PHOTO])
        //            ->where('businessId', 0)
        //            ->select(['url', 'position'])
        //            ->pluck('url', 'position')->toArray();
        //        if (isset($image[UploadFileResourceEnum::TAKE_OUT_HEATMAP])) $heatmap = picturePath($image[UploadFileResourceEnum::TAKE_OUT_HEATMAP]);

        $heatmap = self::getHeatMapByWgNumber($wgNumber);

        $cacheKey   = 'tiger:openShop:heatMap:' . md5(json_encode(['lng' => $lng, 'lat' => $lat]));
        $heatMapDot = Cache::rememberForever($cacheKey, function () use ($lng, $lat) {
            $dir = sys_get_temp_dir() . '/tempHeatMapFile/';
            if (!is_dir($dir)) {
                mkdir($dir);
            }
            $heatmapFilePath = $dir . Str::random() . '.json';
            //获取文件数据
            //外卖预估数据
            $takeOutData = (new WaiMaiAnalysisService())
                ->setLngLat((float)$lng, (float)$lat, 0.8);

            $arr = [];
            $takeOutData->getNearByShop()->each(function ($item) use (&$arr) {
                $arr[] = [
                    'lat'   => $item['lat'],
                    'lng'   => $item['lng'],
                    'count' => $item['orderNum'],
                ];
            });
            file_put_contents($heatmapFilePath, json_encode($arr));
            //文件上传
            $arr = FileUtil::uploadFile($heatmapFilePath);
            @unlink($heatmapFilePath);
            return $arr['url'];
        });


        $amapKey = WangGuiCityByPower::getRandomAmapKey();

        return [
            'sort'  => 65,
            'key'   => 'takeOutEstimate',
            'name'  => '外卖预估',
            'value' => [
                'tab1'    => [
                    'parent' => '',
                    'title'  => '外卖月销预估',
                    'value'  => [
                        [
                            "field"       => "wmHeatMap",
                            "text"        => "外卖热力图",
                            "required"    => false,
                            "input"       => "heatmap",
                            "options"     => [],
                            "icon"        => "",
                            "display"     => "block",
                            "isResource"  => true,
                            "requestData" => [
                                "url"     => config('app.url') . 'openShop/feishu/siteLocation/preserveHeatMap',
                                "methods" => "POST",
                                "data"    => [
                                    "orderNo" => "FY43318"
                                ]
                            ],
                            "zoom"        => 15,
                            "lng"         => $lng,
                            "lat"         => $lat,
                            "dataUrl"     => $heatMapDot,
                            "background"  => "https://restapi.amap.com/v3/staticmap?location=$lng,$lat&zoom=17&size=1600*1600&key=" . $amapKey,
                            "position"    => 100,
                            "disabled"    => true,
                            "desc"        => "外卖热力图说明：点位附近3km全品类门店月销量热力图\n外卖销量预估说明：按照预估订单量乘以系数0.8和1.2，取值外卖销量区间值\n外卖销量预估：按照单据30元估算月实收区间值",
                            "value"       => $heatmap
                        ], [
                            "field"      => "takeOutDoubleSalesVolume",
                            "text"       => "双平台外卖销量预估",
                            "required"   => false,
                            "input"      => "text",
                            "options"    => [],
                            "icon"       => "",
                            "display"    => "block",
                            "isResource" => false,
                            "disabled"   => true,
                            "unit"       => '单',
                            "desc"       => "外卖热力图说明：点位附近3km全品类门店月销量热力图\n外卖销量预估说明：按照预估订单量乘以系数0.8和1.2，取值外卖销量区间值\n外卖销量预估：按照单据30元估算月实收区间值",
                            "value"      => $takeOutDoubleSalesVolume
                        ], [
                            "field"      => "takeOutDoubleSalesVolumeReceived",
                            "text"       => "双平台外卖月实收预估",
                            "required"   => false,
                            "input"      => "text",
                            "options"    => [],
                            "icon"       => "",
                            "display"    => "block",
                            "isResource" => false,
                            "disabled"   => true,
                            "unit"       => '元',
                            "value"      => $takeOutDoubleSalesVolumeReceived
                        ], [
                            "field"      => "mtSalesVolume",
                            "text"       => "美团外卖月销量预估",
                            "required"   => false,
                            "input"      => "text",
                            "options"    => [],
                            "icon"       => "",
                            "display"    => "block",
                            "isResource" => false,
                            "disabled"   => true,
                            "unit"       => '单',
                            "value"      => $mtSalesVolume
                        ], [
                            "field"      => "elmSalesVolume",
                            "text"       => "饿了么外卖月销量预估",
                            "required"   => false,
                            "input"      => "text",
                            "options"    => [],
                            "icon"       => "",
                            "display"    => "block",
                            "isResource" => false,
                            "disabled"   => true,
                            "unit"       => '单',
                            "value"      => $elmSalesVolume
                        ]
                    ]
                ],
                'tab2'    => [
                    'parent' => '',
                    'title'  => '夸父门店外卖月销量Top3',
                    'value'  => [
                        [
                            "field"      => "kfSalesVolume",
                            "text"       => "",
                            "required"   => false,
                            "input"      => "table",
                            "options"    => [],
                            "icon"       => "",
                            "display"    => "block",
                            "isResource" => false,
                            "disabled"   => true,
                            "header"     => [
                                [
                                    'key'   => 'shopName',
                                    'label' => '门店名称',
                                ], [
                                    'key'   => 'distance',
                                    'label' => '距离',
                                    'pixel' => 60
                                ], [
                                    'key'   => 'mtElm',
                                    'label' => '美团/饿了么/双平台',
                                ]
                            ],
                            "value"      => $kfSalesVolume
                        ]
                    ]
                ],
                'tab3'    => [
                    'parent' => '',
                    'title'  => '炸串炸鸡美团外卖月销量Top5',
                    'value'  => [
                        [
                            "field"      => "mtFriedGoods",
                            "text"       => "",
                            "required"   => false,
                            "input"      => "table",
                            "options"    => [],
                            "icon"       => "",
                            "display"    => "block",
                            "isResource" => false,
                            "disabled"   => true,
                            "header"     => [
                                [
                                    'key'   => 'shopName',
                                    'label' => '门店',
                                ], [
                                    'key'   => 'distance',
                                    'label' => '距离',
                                    'pixel' => 60
                                ], [
                                    'key'   => 'mt',
                                    'label' => '美团',
                                    'pixel' => 70
                                ]
                            ],
                            "value"      => $mtFriedGoods
                        ]
                    ]
                ], 'tab4' => [
                    'parent' => '',
                    'title'  => '炸串炸鸡饿了么外卖月销量Top5',
                    'value'  => [
                        [
                            "field"      => "elmFriedGoods",
                            "text"       => "",
                            "required"   => false,
                            "input"      => "table",
                            "options"    => [],
                            "icon"       => "",
                            "display"    => "block",
                            "isResource" => false,
                            "disabled"   => true,
                            "header"     => [
                                [
                                    'key'   => 'shopName',
                                    'label' => '门店名称',
                                ], [
                                    'key'   => 'distance',
                                    'label' => '距离',
                                    'pixel' => 60
                                ], [
                                    'key'   => 'elm',
                                    'label' => '饿了么',
                                    'pixel' => 70
                                ]
                            ],
                            "value"      => $elmFriedGoods
                        ]
                    ]
                ]
            ],

        ];
    }

    public static function brandTree()
    {
        $brandTree = ConfigModel::query()
            ->where('module', ConfigModel::MODULE_WANGGUI)
            ->where('name', ConfigModel::BRAND_TREE)
            ->value('value');
        return json_decode($brandTree, true);
    }

    public static function uploadHandDrawImg(array $fileArr, int $siteId)
    {
        $data = [
            'businessId'   => $siteId,
            'module'       => ResourcesModel::MODULE_TYPE_MOVING_LING_MARKING_DESC,
            'business'     => ResourcesModel::BUSINESS_MOVING_LING_MARKING_DESC,
            'name'         => UploadFileResourceEnum::MOVING_LING_MARKING_DESC,
            'url'          => $fileArr['path'],
            'isPublic'     => 1,
            'extra'        => json_encode($fileArr, true),
            'createdAt'    => time(),
            'updatedAt'    => time(),
            'createdByUid' => $authUser['userId'] ?? 0,
            'updatedByUid' => $authUser['userId'] ?? 0,
        ];
        ResourcesModel::query()->insert([$data]);
    }

    public static function getBusinessBoundaryByCityCode($cityCode, $occupyStatus, $capacity)
    {
        $specialCityCodeJson = (string)ConfigModel::query()
            ->where('module', 'businessAoi')
            ->where('name', 'cityCodeConvert')
            ->value('value');
        $specialCityCodeArr  = json_decode($specialCityCodeJson, true);
        $cityCode            = $specialCityCodeArr[$cityCode] ?? $cityCode;
        return BusinessAoiModel::query()
            ->where('cityCode', $cityCode)
            ->when(strlen($occupyStatus), function ($query) use ($occupyStatus){
                $query->whereIn('occupyStatus', explode(',', $occupyStatus));
            })
            ->when(strlen($capacity), function ($query) use ($capacity){
                $capacities = explode(',', $capacity);
                $query->where(function ($query) use ($capacities) {
                    foreach ($capacities as $value) {
                        switch ($value) {
                            case 1:
                                $query->orWhereBetween('capacity', [0, 2]);
                                break;
                            case 2:
                                $query->orWhereBetween('capacity', [3, 5]);
                                break;
                            case 3:
                                $query->orWhereBetween('capacity', [6, 10]);
                                break;
                            case 4:
                                $query->orWhere('capacity', '>', 10);
                                break;
                        }
                    }
                });
            })
            ->where('level', 'bizcircle')
            ->get()
            ->map(function (BusinessAoiModel $businessAoiModel) {
                return [
                    'id'               => $businessAoiModel->id,
                    'name'             => $businessAoiModel->name,
                    'cityCode'         => $businessAoiModel->cityCode,
                    'lng'              => $businessAoiModel->lng,
                    'lat'              => $businessAoiModel->lat,
                    'occupyStatus'     => $businessAoiModel->occupyStatus,
                    'occupyStatusText' => $businessAoiModel->occupyStatusText,
                    'boundary'         => json_decode($businessAoiModel->boundary, true)
                ];
            })->toArray();
        // return Cache::remember('wanggui:business:boundary:cache:' . $cityCode, now()->addSeconds(120), function () use ($cityCode) {
        //     ini_set('memory_limit', '512M');
        //     return BusinessAoiModel::query()
        //         ->where('cityCode', $cityCode)
        //         ->where('level', 'bizcircle')
        //         ->get()
        //         ->map(function (BusinessAoiModel $businessAoiModel) {
        //             return [
        //                 'id'               => $businessAoiModel->id,
        //                 'name'             => $businessAoiModel->name,
        //                 'cityCode'         => $businessAoiModel->cityCode,
        //                 'lng'              => $businessAoiModel->lng,
        //                 'lat'              => $businessAoiModel->lat,
        //                 'occupyStatus'     => 0,
        //                 'occupyStatusText' => '未占位',
        //                 'boundary'         => json_decode($businessAoiModel->boundary, true)
        //             ];
        //         })->toArray();
        // });
    }

    //获得网规点位热力图
    public static function getHeatMapByWgNumber(string $wgNumber)
    {
        try {
            //获得外卖热力图图片
            $image = (string)ResourcesModel::query()
                ->where('name', $wgNumber)
                ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                ->where('business', ResourcesModel::BUSINESS_WG_HEAT_MAP)
                ->value('url');

            if (strlen($image)) {
                $heatMapImage = picturePath($image);
            } else {
                //生成热力图
                //获得网规编号前两位数据
                $prefix = substr($wgNumber, 0, 2);
                if ($prefix == 'KF') {
                    $shopCode = (int)substr($wgNumber, 0, -4);
                    GuanyuanDataService::setTimeOut(20);
                    try {
                        $shopInfo = GuanyuanDataService::newShopList($shopCode)[0] ?? [];
                    } catch (\Exception $exception) {
                        $shopInfo = [];
                    }
                    $lng = $shopInfo['门店经度'] ?? 0;
                    $lat = $shopInfo['门店纬度'] ?? 0;
                } else {
                    $className = SandTableEnum::PREFIX_GET_TABLE_MODEL_MAPPING[$prefix] ?? null;
                    if (null === $className) {
                        return '';
                    }
                    $model = $className::query()
                        ->where('wgNumber', $wgNumber)
                        ->first();
                    $lng   = $model->lng;
                    $lat   = $model->lat;
                }
                if (!$lng || !$lat) {
                    return 'https://file.51kuafu.com/52/42/6f191617b85d80427702dcf6e938872fa6bbb4552898631ca5a13787bdab.png';
                }

                // 获得高德地图的key
                $amapkey     = WangGuiCityByPower::getRandomAmapKey();
                $amapUrlTemp = 'https://restapi.amap.com/v3/staticmap?location=%s,%s&markers=-1,https://file.51kuafu.com/9a/11/8f2998d7c8a1032f6eb1ebf343cd5ba8f8658c237c202c76edbb83578cc9.png,0:%s,%s&zoom=15&size=1024*1024&labels=%s,3,1,20,0x000000,0xFFF733:%s,%s&key=' . $amapkey;
                $url         = sprintf($amapUrlTemp, $lng, $lat, $lng, $lat, '', $lng, ($lat + 0.001));
                $png         = sys_get_temp_dir() . '/' . Str::random() . '.png';
                (new Client())->get($url, [
                    'sink' => $png,
                ]);
                $heatMap      = FileUtil::uploadFile(HeatMapService::makeHeatMap($png, $lng, $lat));
                $heatMapImage = $heatMap['url'] ?? '';
                //上传到resources
                $resource           = ResourcesModel::query()->firstOrNew([
                    'name' => $wgNumber
                ]);
                $resource->module   = ResourcesModel::MODULE_TYPE_WG_AUDIT;
                $resource->business = ResourcesModel::BUSINESS_WG_HEAT_MAP;
                $resource->name     = $wgNumber;
                $resource->url      = $heatMap['path'];
                $resource->isPublic = 1;
                $resource->save();
                @unlink($heatMapImage);
            }
        } catch (\ErrorException $exception) {
            $heatMapImage = 'https://file.51kuafu.com/52/42/6f191617b85d80427702dcf6e938872fa6bbb4552898631ca5a13787bdab.png';
        }
        return $heatMapImage;
    }


    public static function floatCard(string $type, int $id): array
    {
        // 通过type和ID获得模型详情
        if ($type == SandTableEnum::KF_MODEL_SAND_TABLE) {
            //            if (Cache::has('openShop:sandTable:kfShop:Cache:code:' . (int)$id)) {
            //                return Cache::get('openShop:sandTable:kfShop:Cache:code:' . (int)$id);
            //            }
            //            //获得观远的门店数据
            //            $shopCode         = str_pad($id, 4, '0', STR_PAD_LEFT);
            //            try {
            //                GuanyuanDataService::setTimeOut(10);
            //                $guanyuanDataList = GuanyuanDataService::getShopBusinessInfoByCode([$shopCode]);
            //            } catch (\Exception $exception) {
            //                throw new ResponseHttpException(504, null, '获取门店详情超时,请稍后再试');
            //            }
            //            $maxDate          = 0;
            //            $maxItem          = [];
            //            foreach ($guanyuanDataList as $guanyuanData) {
            //                $date = strtotime($guanyuanData['日期']);
            //                if ($date > $maxDate) {
            //                    $maxDate = $date;
            //                    $maxItem = $guanyuanData;
            //                }
            //            }

            // 获得该门店最近的营业额
            $turnover = (string)GuanyuanSyncShopBusinessModel::query()
                ->where('code', $id)
                ->orderByDesc('date')
                ->select(['date', 'shopGrade'])
                ->value('shopGrade');

            $data = SandTableService::getKfShopCardInfo($id, ['门店分级' => $turnover]);
        } else {
            //点位
            if (!isset(SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type])) {
                self::throwErr('类型错误');
            }
            $model      = SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type]::query();
            $modelQuery = $model->where('id', $id)->with(['logRel.resourceRelUsedToShow', 'logRel.resourceRelByCover', 'resourceWithMapRel'])->first();
            if ($modelQuery == null) {
                self::throwErr('获取网规点位详情失败');
            }
            $cover = SandTableService::getDefaultCoverImage($modelQuery->wgNumber);   //先获得地图图片
            optional($modelQuery->logRel)->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$cover) {
                $locationExamineLogModel->resourceRelByCover->each(function (ResourcesModel $resourcesModel) use (&$cover) {
                    $fileType = json_decode($resourcesModel->extra, true)['type'] ?? '-';
                    if ($resourcesModel->name == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $fileType == 'image') {
                        $cover = picturePath($resourcesModel->url);
                    }
                });
            });
            $status   = '待评估';
            $wgNumber = $modelQuery->wgNumber;
            if ($type == 'product') {
                OpenShopSiteLocationExamineLogModel::query()
                    ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT)
                    ->orderBy('updatedAt', 'asc')
                    ->with(['resourceRelUsedToShow', 'wangguiSiteDistrictRel.resourceRel'])
                    ->where('orderNo', $wgNumber)
                    ->get()
                    ->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$status) {
                        $status = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                    });
            } else {
                optional(
                    optional($modelQuery->logRel)->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$status) {
                        $status = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                    })
                );
            }

            switch ($type) {
                case 'mallProgramming':
                    $label   = array_merge(
                        (mb_strlen($modelQuery->topList) ? [$modelQuery->topList] : [])
                    );
                    $special = [
                        [
                            'name'  => '店铺总数',
                            'value' => $modelQuery->shopTotalCount,
                        ], [
                            'name'  => '美食店铺占比',
                            'value' => $modelQuery->foodRatio ? ($modelQuery->foodRatio * 100 . '%') : 0,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'streetProgramming':
                case 'communityProgramming':
                case 'parkProgramming':
                    $label   = [];
                    $special = [
                        [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'townProgramming':
                    $label   = array_merge(
                        ($modelQuery->shopCountRank ? ['商超数排名第' . $modelQuery->shopCountRank] : []),
                        ($modelQuery->qianqiangTownRank ? ['千强镇第' . $modelQuery->qianqiangTownRank . '名'] : [])
                    );
                    $special = [
                        [
                            'name'  => '人口密度',
                            'value' => round($modelQuery->peopleDensity, 1),
                        ], [
                            'name'  => '人口密度排名',
                            'value' => $modelQuery->peopleDensityRank,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'schoolProgramming':
                    $label   = array_merge(
                        ($modelQuery->doubleFirstClass == '是' ? ['双一流'] : []),
                        ($modelQuery->project985 == '是' ? ['985'] : []),
                        ($modelQuery->project211 == '是' ? ['211'] : []),
                        ($modelQuery->strongBasis == '是' ? ['强基'] : [])
                    );
                    $special = [
                        [
                            'name'  => '院校类型',
                            'value' => $modelQuery->schoolType,
                        ], [
                            'name'  => '面积',
                            'value' => $modelQuery->space . '亩',
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'product':
                    $label   = [];
                    $special = [
                        [
                            'name'  => '开业时间',
                            'value' => $modelQuery->openingTime ?: '-',
                        ], [
                            'name'  => '营业时间',
                            'value' => $modelQuery->openingTime ? Carbon::parse($modelQuery->openingTime)->diff(Carbon::now())->format('%y年%m个月') : '-'
                        ]
                    ];
                    $key     = ProgrammingEnum::BRAND_SHOP_MAPPING[$modelQuery->brand] ?? 'product';
                    break;
                default:
                    $label   = [];
                    $special = [];
            }

            $data = [
                'cover'          => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                'name'           => $modelQuery->nameText,
                'type'           => $type,
                'key'            => $key ?? (string)array_search(get_class($modelQuery), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                'status'         => $status,
                'openPotential'  => $modelQuery->status,
                'wgNumber'       => $modelQuery->wgNumber,
                'label'          => $label,
                'settleIn'       => $modelQuery->settle ? '已入驻' : '',
                'special'        => $special,
                'grade'          => ProgrammingEnum::GRADE_MAPPING[$modelQuery->grade] ?? '',
                'lng'            => $modelQuery->lng,
                'lat'            => $modelQuery->lat,
                'province'       => $modelQuery->province,
                'city'           => $modelQuery->city,
                'district'       => $modelQuery->district,
                'recommendFloor' => $modelQuery->recommendFloor ?: '',  //推荐楼层
                'address'        => $modelQuery->address,
            ];
        }

        // todo 新加内容从这里判断


        return $data;
    }

    public static function cityPintByPc(string $city): array
    {
        $shopOpen = $shopPause = $shopPreparatory = $shopSite = $shopClose = [];

        $shopList = GuanyuanSyncShopListModel::query()
            ->where('city', 'like', mb_substr($city, 0, 2) . '%')
            ->get();

        foreach ($shopList as $shopInfo) {
            $data = [
                'id'           => $shopInfo->code,
                'type'         => SandTableEnum::KF_MODEL_SAND_TABLE,
                'lat'          => $shopInfo->lat,
                'lng'          => $shopInfo->lng,
                'boundary'     => [],
                'status'       => $shopInfo->status,
                'name'         => $shopInfo->name,
                'openBusinessDate' => (string)$shopInfo->openBusinessDate,
                'storeType'    => $shopInfo->storeType,
                'area'         => $shopInfo->area,
                'district'     => $shopInfo->district,
                'actualIncome' => (int)$shopInfo->actualIncome,
                'grade'        => $shopInfo->shopGrade,
            ];
            switch ($shopInfo->status) {
                case '正常营业':
                    $shopOpen[] = $data;
                    break;
                case '暂停营业':
                    $shopPause[] = $data;
                    break;
                case '筹备中':
                    $shopPreparatory[] = $data;
                    break;
                case '选址中':
                    $shopSite[] = $data;
                    break;
                case '闭店':
                    $shopClose[] = $data;
                    break;
            }
        }

        //商场信息
        $mallData = [];
        SiteLocationMallModel::query()
            ->where('grade', '>', 0)
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', mb_substr($city, 0, 2) . '%');
            })
            ->select(['id', 'lng', 'lat', 'shopNum', 'mallName', 'grade', 'district'])
            ->get()
            ->each(function (SiteLocationMallModel $siteLocationMallModel) use (&$mallData) {
                if ($siteLocationMallModel->lng && $siteLocationMallModel->lat) {
                    $mallData[] = [
                        'id'       => $siteLocationMallModel->id,
                        'name'     => $siteLocationMallModel->mallName,
                        'type'     => 'mallProgramming',
                        'lat'      => $siteLocationMallModel->lat,
                        'lng'      => $siteLocationMallModel->lng,
                        'district' => $siteLocationMallModel->district,
                        'shopNum'  => $siteLocationMallModel->shopNum,
                        'boundary' => [],
                        'grade'    => ProgrammingEnum::PC_GRADE_MAPPING[(int)$siteLocationMallModel->grade] ?? '',
                    ];
                }
            });


        //产业园区信息
        $nationalIndustrialParkData = [];
        MapNationalIndustrialParkModel::query()
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', mb_substr($city, 0, 2) . '%');
            })
            ->select(['id', 'lon', 'lat', 'grade', 'shopNum', 'name', 'district'])
            ->get()
            ->each(function (MapNationalIndustrialParkModel $mapNationalIndustrialParkModel) use (&$nationalIndustrialParkData) {
                if ($mapNationalIndustrialParkModel->lon && $mapNationalIndustrialParkModel->lat) {
                    $nationalIndustrialParkData[] = [
                        'id'       => $mapNationalIndustrialParkModel->id,
                        'name'     => $mapNationalIndustrialParkModel->name,
                        'type'     => 'parkProgramming',
                        'lat'      => $mapNationalIndustrialParkModel->lat,
                        'lng'      => $mapNationalIndustrialParkModel->lon,
                        'district' => $mapNationalIndustrialParkModel->district,
                        'shopNum'  => $mapNationalIndustrialParkModel->shopNum,
                        'boundary' => [],
                        'grade'    => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalIndustrialParkModel->grade] ?? '',
                    ];
                }
            });


        //高校
        $nationalUniversitiesData = [];
        MapNationalUniversitiesModel::query()
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', mb_substr($city, 0, 2) . '%');
            })
            ->select(['id', 'lon', 'lat', 'grade', 'shopNum', 'name', 'district'])
            ->get()
            ->each(function (MapNationalUniversitiesModel $mapNationalUniversitiesModel) use (&$nationalUniversitiesData) {
                if ($mapNationalUniversitiesModel->lon && $mapNationalUniversitiesModel->lat) {
                    $nationalUniversitiesData[] = [
                        'id'       => $mapNationalUniversitiesModel->id,
                        'name'     => $mapNationalUniversitiesModel->name,
                        'type'     => 'schoolProgramming',
                        'lat'      => $mapNationalUniversitiesModel->lat,
                        'lng'      => $mapNationalUniversitiesModel->lon,
                        'district' => $mapNationalUniversitiesModel->district,
                        'shopNum'  => $mapNationalUniversitiesModel->shopNum,
                        'boundary' => [],
                        'grade'    => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalUniversitiesModel->grade] ?? '',
                    ];
                }
            });


        //街道
        $streetData = [];
        MapNationalStreetModel::query()
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', mb_substr($city, 0, 2) . '%');
            })
            ->select(['id', 'lng', 'lat', 'grade', 'coords', 'shopNum', 'address', 'district'])
            ->get()
            ->each(function (MapNationalStreetModel $mapNationalStreetModel) use (&$streetData) {
                if ($mapNationalStreetModel->lng && $mapNationalStreetModel->lat) {
                    $streetData[] = [
                        'id'       => $mapNationalStreetModel->id,
                        'name'     => $mapNationalStreetModel->address,
                        'type'     => 'streetProgramming',
                        'lat'      => $mapNationalStreetModel->lat,
                        'lng'      => $mapNationalStreetModel->lng,
                        'district' => $mapNationalStreetModel->district,
                        'shopNum'  => $mapNationalStreetModel->shopNum,
                        'boundary' => json_decode($mapNationalStreetModel->coords, true),
                        'grade'    => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalStreetModel->grade] ?? '',
                    ];
                }
            });



        //社区
        $communityData = [];
        MapNationalCommunityModel::query()
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', mb_substr($city, 0, 2) . '%');
            })
            ->select(['id', 'lng', 'lat', 'grade', 'coords', 'shopNum', 'address', 'district'])
            ->get()
            ->each(function (MapNationalCommunityModel $mapNationalCommunityModel) use (&$communityData) {
                if ($mapNationalCommunityModel->lng && $mapNationalCommunityModel->lat) {
                    $communityData[] = [
                        'id'       => $mapNationalCommunityModel->id,
                        'name'     => $mapNationalCommunityModel->address,
                        'type'     => 'communityProgramming',
                        'lat'      => $mapNationalCommunityModel->lat,
                        'lng'      => $mapNationalCommunityModel->lng,
                        'district' => $mapNationalCommunityModel->district,
                        'shopNum'  => $mapNationalCommunityModel->shopNum,
                        'boundary' => json_decode($mapNationalCommunityModel->coords, true),
                        'grade'    => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalCommunityModel->grade] ?? '',
                    ];
                }
            });


        //乡镇
        $townData = [];
        MapTownshipPlanAreaModel::query()
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', mb_substr($city, 0, 2) . '%');
            })
            ->select(['id', 'lng', 'lat', 'grade', 'shopNum', 'area', 'district'])
            ->get()
            ->each(function (MapTownshipPlanAreaModel $mapTownshipPlanAreaModel) use (&$townData) {
                if ($mapTownshipPlanAreaModel->lng && $mapTownshipPlanAreaModel->lat) {
                    $townData[] = [
                        'id'       => $mapTownshipPlanAreaModel->id,
                        'name'     => $mapTownshipPlanAreaModel->area,
                        'type'     => 'townProgramming',
                        'lat'      => $mapTownshipPlanAreaModel->lat,
                        'lng'      => $mapTownshipPlanAreaModel->lng,
                        'district' => $mapTownshipPlanAreaModel->district,
                        'shopNum'  => $mapTownshipPlanAreaModel->shopNum,
                        'boundary' => [],
                        'grade'    => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapTownshipPlanAreaModel->grade] ?? '',
                    ];
                }
            });

        //关联品牌数据信息
        $otherBrandShopData = [];
        MapNationalBrandShopModel::query()
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', mb_substr($city, 0, 2) . '%');
            })
            ->select(['id', 'lon', 'lat', 'brand', 'name', 'district'])
            ->get()
            ->each(function (MapNationalBrandShopModel $mapNationalBrandShopModel) use (&$otherBrandShopData) {
                if ($mapNationalBrandShopModel->lon && $mapNationalBrandShopModel->lat) {
                    $otherBrandShopData[] = [
                        'id'       => $mapNationalBrandShopModel->id,
                        'name'     => strpos($mapNationalBrandShopModel->name, $mapNationalBrandShopModel->brand) === false ? ($mapNationalBrandShopModel->brand . '·' . $mapNationalBrandShopModel->name) : $mapNationalBrandShopModel->name,
                        'brand'    => $mapNationalBrandShopModel->brand,
                        'type'     => 'product',
                        'lat'      => $mapNationalBrandShopModel->lat,
                        'lng'      => $mapNationalBrandShopModel->lon,
                        'district' => $mapNationalBrandShopModel->district,
                        'boundary' => [],
                        'grade'    => '',
                    ];
                }
            });
        $brandShopData = [];
        $pinyinData    = [];
        if (count($otherBrandShopData)) {
            foreach ($otherBrandShopData as $v) {
                if (isset($pinyinData[$v['brand']])) {
                    $brandKey = $pinyinData[$v['brand']];
                } else {
                    $brandKey                = ProgrammingEnum::BRAND_SHOP_MAPPING[$v['brand']] ?? 'product';
                    $pinyinData[$v['brand']] = $brandKey;
                }
                $brandShopData[$brandKey][] = $v;
            }
        }

        $res = [
            'shopOpen'                   => $shopOpen,
            'shopPause'                  => $shopPause,
            'shopPreparatory'            => $shopPreparatory,
            'shopSite'                   => $shopSite,
            'shopClose'                  => $shopClose,
            'mallData'                   => $mallData,
            'streetData'                 => $streetData,
            'communityData'              => $communityData,
            'townData'                   => $townData,
            'nationalIndustrialParkData' => $nationalIndustrialParkData,
            'nationalUniversitiesData'   => $nationalUniversitiesData,
        ];

        return array_merge($res, $brandShopData);
    }

    public static function getPoint(string $city, string $northEast, string $center, string $southWest): array
    {
        // 查询两个点的距离
        //        Redis::geoadd('tmp:dist:' . md5($center . $southWest), explode(',', $center)[0], explode(',', $center)[1], 'local:' . $center);
        //        Redis::geoadd('tmp:dist:' . md5($center . $southWest), explode(',', $southWest)[0], explode(',', $southWest)[1], 'local:' . $southWest);
        //        $radius = ceil(Redis::geodist('tmp:dist:' . md5($center . $southWest), 'local:' . $center, 'local:' . $southWest, 'm'));
        //
        //        // 删除redis的key
        //        Redis::del('tmp:dist:' . md5($center . $southWest));

        // 设置城市点位缓存 方便不同距离查询
        $cityPointInfo = Cache::remember('wanggui:cityPointInfo:' . $city, 3600 * 5, function () use ($city) {
            return self::cityPintByPc($city);
        });

        // 将经纬度存入redis 方便距离查询  已加入缓存  直接查询
        //foreach ($cityPointInfo as $cityPointType => $cityPoint) {
        //    foreach ($cityPoint as $point) {
        //        Redis::geoAdd('wanggui:cityPointLocation:' . $city, $point['lng'], $point['lat'], $cityPointType . '-' . $point['id']);
        //    }
        //}

        // 查询
        //        $points = Redis::georadius('wanggui:cityPointLocation:' . $city, explode(',', $center)[0], explode(',', $center)[1], $radius, 'm');
        //
        //        $giveKey = [];
        //        foreach ($points as $point) {
        //            $pointParamArr                = explode('-', $point);
        //            $giveKey[$pointParamArr[0]][] = $pointParamArr[1];
        //        }
        //
        //        $data = [];
        //
        //        foreach ($cityPointInfo as $type => $cityPoint) {
        //            if (!isset($giveKey[$type])) {
        //                continue;
        //            }
        //            $data[$type] = collect($cityPoint)->whereIn('id', $giveKey[$type])->values()->toArray();
        //        }

        return $cityPointInfo;
    }


    /**
     * 获得附近点位
     * @param float $lng
     * @param float $lat
     * @param int $distance
     * @param string $city
     * @return array
     */
    public static function nearbyByPc(float $lng, float $lat, int $distance, string $city): array
    {
        $city = str_replace('城区', '市', $city);
        if (mb_strlen($city) == 2 && strpos($city, '市') === false) {
            $city = $city . '市';
        }
        $data   = [];
        $points = Redis::georadius('wanggui:cityPointLocation:' . $city, $lng, $lat, $distance, 'm', ['WITHDIST', 'ASC']);

        // 拥有点位
        $giveKey = [];

        // 点位距离
        $distancePointList = [];

        foreach ($points as $point) {
            $distancePointList[$point[0]] = (int)$point[1];
            $pointParamArr                = explode('-', $point[0]);
            $giveKey[$pointParamArr[0]][] = $pointParamArr[1];
        }
        // 城市点位缓存
        $cityPointInfo = Cache::remember('wanggui:cityPointInfo:' . $city, 3600 * 5, function () use ($city) {
            return self::cityPintByPc($city);
        });

        // 竞品
        $competition = [];

        // 互补品
        $complement = [];
        foreach ($cityPointInfo as $type => $cityPoint) {
            if (!isset($giveKey[$type])) {
                continue;
            }

            $pointArr = collect($cityPoint)->whereIn('id', $giveKey[$type])->map(function ($point) use ($type, $distancePointList) {
                if ($point['type'] == 'kfShop') {
                    $point['name'] = $point['status'] . '-' . $point['name'];
                }
                $point['distance'] = $distancePointList[$type . '-' . $point['id']] ?? 0;
                return $point;
            })->sortBy('distance')->values()->toArray();

            // 针对竞品互补品特殊处理
            if (in_array(array_search($type, ProgrammingEnum::BRAND_SHOP_MAPPING), ProgrammingEnum::BRAND_SAND_TABLE_COMPETITIVE_PRODUCTS_MAPPING)) {
                $competition = array_merge($competition, $pointArr);
                continue;
            }
            if (in_array(array_search($type, ProgrammingEnum::BRAND_SHOP_MAPPING), ProgrammingEnum::BRAND_SAND_TABLE_COMPLEMENTARY_PRODUCTS_MAPPING)) {
                $complement = array_merge($complement, $pointArr);
                continue;
            }

            $data[$type] = $pointArr;
        }

        $kfShop = [];
        foreach ($data as $key => $datum) {
            if (in_array($key, array_keys(ProgrammingEnum::PC_TYPE_LIST_HEAD_KF_CHILDREN_MAPPING))) {
                $kfShop = array_merge($kfShop, $datum);
                unset($data[$key]);
            }
        }

        $data['kfShop']      = collect($kfShop)->sortBy('distance')->values()->toArray();
        $data['competition'] = collect($competition)->sortBy('distance')->values()->toArray();
        $data['complement']  = collect($complement)->sortBy('distance')->values()->toArray();

        return $data;
    }

    public static function listByPc(string $city, string $type, int $pageNum, int $pageSize, string $status, string $gradeShop, string $shopType, string $area, string $gradeWanggui, string $name, string $setInType, string $competition, string $complement, string $actualIncome, string $shopOpenStartDate, string $shopOpenEndDate): array
    {
        $city = str_replace('城区', '市', $city);

        switch ($type) {
            case'kfShop':
                $paginate = GuanyuanSyncShopListModel::query()
                    ->where('city', $city)
                    ->when($status, function ($query) use ($status) {
                        $param     = [];
                        $statusArr = explode(',', $status);
                        foreach ($statusArr as $item) {
                            $param[] = ProgrammingEnum::PC_TYPE_LIST_HEAD_KF_CHILDREN_MAPPING[$item] ?? '';
                        }
                        $query->whereIn('status', $param);
                    })
                    ->when($gradeShop, function ($query) use ($gradeShop) {
                        $query->whereIn('shopGrade', explode(',', $gradeShop));
                    })
                    ->when(mb_strlen($name), function ($query) use ($name) {
                        $query->where('name', 'like', "%{$name}%");
                    })
                    ->when($shopType, function ($query) use ($shopType) {
                        $query->whereIn('storeType', explode(',', $shopType));
                    })
                    ->when(strlen($shopOpenStartDate) && strlen($shopOpenEndDate), function ($query) use ($shopOpenStartDate, $shopOpenEndDate) {
                        $query->whereBetween('openBusinessDate', [$shopOpenStartDate, $shopOpenEndDate]);
                    })
                    ->where(function ($query) use ($area) {
                        $query->when($area, function ($q) use ($area) {
                            $areaArr = explode(',', $area);
                            foreach ($areaArr as $k => $item) {
                                $itemArr = explode('-', $item);
                                if ($k == 0) {
                                    $q->whereBetween('area', [$itemArr[0], $itemArr[1]]);
                                } else {
                                    $q->orWhereBetween('area', [$itemArr[0], $itemArr[1]]);
                                }
                            }
                        });
                    })
                    ->where(function ($query) use ($actualIncome) {
                        $query->when($actualIncome, function ($q) use ($actualIncome) {
                            $actualIncomeArr = explode(',', $actualIncome);
                            foreach ($actualIncomeArr as $k => $item) {
                                $itemArr = explode('-', $item);
                                if ($k == 0) {
                                    $q->whereBetween('actualIncome', [$itemArr[0], $itemArr[1]]);
                                } else {
                                    $q->orWhereBetween('actualIncome', [$itemArr[0], $itemArr[1]]);
                                }
                            }
                        });
                    })
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $orderNos = $paginate->pluck('orderNo', 'code')->toArray();


                $defaultImage = self::getShopImageByShopCode([], $orderNos);

                $list = $paginate->map(function (GuanyuanSyncShopListModel $guanyuanSyncShopListModel) use (&$orderNos, $defaultImage) {
                    // 开业时长
                    $openTime = '-';
                    if ($guanyuanSyncShopListModel->openBusinessDate) {
                        $openBusinessDateArr = explode('-', $guanyuanSyncShopListModel->openBusinessDate);
                        $openTime            = Carbon::createFromDate($openBusinessDateArr[0], $openBusinessDateArr[1], $openBusinessDateArr[2])->diff(Carbon::now())->format('%y年%m个月');
                    }
                    $orderNos[$guanyuanSyncShopListModel->code] = $guanyuanSyncShopListModel->orderNo;
                    // 额外的数据
                    return [
                        'id'           => $guanyuanSyncShopListModel->code,
                        'type'         => SandTableEnum::KF_MODEL_SAND_TABLE,
                        'lat'          => $guanyuanSyncShopListModel->lat,
                        'lng'          => $guanyuanSyncShopListModel->lng,
                        'boundary'     => [],
                        'status'       => $guanyuanSyncShopListModel->status,
                        'name'         => $guanyuanSyncShopListModel->name,
                        'storeType'    => $guanyuanSyncShopListModel->storeType,
                        'area'         => $guanyuanSyncShopListModel->area,
                        'actualIncome' => (int)$guanyuanSyncShopListModel->actualIncome,
                        'grade'        => $guanyuanSyncShopListModel->shopGrade,
                        'label'        => collect([
                            $guanyuanSyncShopListModel->status,
                            $guanyuanSyncShopListModel->siteLocationType ?: null,
                            $guanyuanSyncShopListModel->storeType ?: null,
                            $guanyuanSyncShopListModel->cashierSystem ?: null
                        ])->filter()->values()->toArray(),
                        'special'      => [
                            [
                                'name'  => '门店面积',
                                'value' => $guanyuanSyncShopListModel->area ?: '-',
                            ],
                            [
                                'name'  => '开业时长',
                                'value' => $openTime
                            ]
                        ],
                        'head'         => $guanyuanSyncShopListModel->relocationMark,
                        'image'        => $defaultImage[$guanyuanSyncShopListModel->code] ?? SandTableEnum::DEFAULT_COVER_IMAGE_BASIC,
                        'province'     => $guanyuanSyncShopListModel->province,
                        'city'         => $guanyuanSyncShopListModel->city,
                        'district'     => $guanyuanSyncShopListModel->district,
                    ];
                })->toArray();
                break;
            case 'mallData':
                $paginate = SiteLocationMallModel::query()
                    ->where('city', 'like', mb_substr(str_replace('市', '', $city), 0, 2) . "%")
                    ->when($gradeWanggui, function ($query) use ($gradeWanggui) {
                        $param     = [];
                        $statusArr = explode(',', $gradeWanggui);
                        foreach ($statusArr as $item) {
                            $param[] = array_search($item, ProgrammingEnum::PC_GRADE_MAPPING);
                        }
                        $query->whereIn('grade', $param);
                    })
                    ->when($name, function ($query) use ($name) {
                        $query->where('mallName', 'like', "%{$name}%");
                    })
                    ->when(mb_strlen($setInType), function ($query) use ($setInType) {
                        $setInTypeArr = explode(',', $setInType);
                        if (count($setInTypeArr) != 2) {
                            if ($setInType == 0) {
                                $query->where('shopNum', 0);
                            } elseif ($setInType == 1) {
                                $query->where('shopNum', '>', 0);
                            }
                        }
                    })
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $list = $paginate->map(function (SiteLocationMallModel $siteLocationMallModel) {
                    //获得最新的评估记录
                    $latestAudit = null;
                    $auditCover  = optional($siteLocationMallModel->resourceWithMapRel)->url ? picturePath($siteLocationMallModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                    if (count($siteLocationMallModel->logRel)) {
                        $latestAudit = collect($siteLocationMallModel->logRel)->sortByDesc('updatedAt')->first();
                        if (count($latestAudit->resourceRelByCover)) {
                            foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                $auditCover = picturePath($resourceRelByCover->url);
                                break;
                            }
                        }
                    }

                    return [
                        'id'             => $siteLocationMallModel->id,
                        'name'           => $siteLocationMallModel->mallName,
                        'type'           => 'mallProgramming',
                        'lat'            => $siteLocationMallModel->lat,
                        'lng'            => $siteLocationMallModel->lng,
                        'shopNum'        => $siteLocationMallModel->shopNum,
                        'boundary'       => [],
                        'grade'          => ProgrammingEnum::PC_GRADE_MAPPING[(int)$siteLocationMallModel->grade] ?? '',
                        'label'          => array_merge((mb_strlen($siteLocationMallModel->topList) ? [$siteLocationMallModel->topList] : [])),
                        'head'           => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)optional($latestAudit)->openPotential] ?? '未评估',
                        'image'          => $auditCover,
                        'special'        => [
                            [
                                'name'  => '店铺总数',
                                'value' => $siteLocationMallModel->shopTotalCount,
                            ], [
                                'name'  => '美食店铺占比',
                                'value' => $siteLocationMallModel->foodRatio ? ($siteLocationMallModel->foodRatio * 100 . '%') : 0,
                            ], [
                                'name'  => '夸父门店数',
                                'value' => $siteLocationMallModel->shopNum,
                            ]
                        ],
                        'openPotential'  => (float)optional($latestAudit)->openPotential,
                        'province'       => $siteLocationMallModel->province,
                        'recommendFloor' => $siteLocationMallModel->recommendFloor,
                        'city'           => $siteLocationMallModel->city,
                        'district'       => $siteLocationMallModel->district,
                    ];
                })->toArray();
                break;
            case 'streetData':
                $paginate = MapNationalStreetModel::query()
                    ->where('city', 'like', mb_substr(str_replace('市', '', $city), 0, 2) . "%")
                    ->when($gradeWanggui, function ($query) use ($gradeWanggui) {
                        $param     = [];
                        $statusArr = explode(',', $gradeWanggui);
                        foreach ($statusArr as $item) {
                            $param[] = array_search($item, ProgrammingEnum::PC_GRADE_MAPPING);
                        }
                        $query->whereIn('grade', $param);
                    })
                    ->when($name, function ($query) use ($name) {
                        $query->where('address', 'like', "%{$name}%");
                    })
                    ->when(mb_strlen($setInType), function ($query) use ($setInType) {
                        $setInTypeArr = explode(',', $setInType);
                        if (count($setInTypeArr) != 2) {
                            if ($setInType == 0) {
                                $query->where('shopNum', 0);
                            } elseif ($setInType == 1) {
                                $query->where('shopNum', '>', 0);
                            }
                        }
                    })
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $list = $paginate->map(function (MapNationalStreetModel $mapNationalStreetModel) {
                    // 获得最新的评估记录
                    $latestAudit = null;
                    $auditCover  = optional($mapNationalStreetModel->resourceWithMapRel)->url ? picturePath($mapNationalStreetModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                    if (count($mapNationalStreetModel->logRel)) {
                        $latestAudit = collect($mapNationalStreetModel->logRel)->sortByDesc('updatedAt')->first();
                        if (count($latestAudit->resourceRelByCover)) {
                            foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                $auditCover = picturePath($resourceRelByCover->url);
                                break;
                            }
                        }
                    }
                    return [
                        'id'            => $mapNationalStreetModel->id,
                        'name'          => $mapNationalStreetModel->address,
                        'type'          => 'streetProgramming',
                        'lat'           => $mapNationalStreetModel->lat,
                        'lng'           => $mapNationalStreetModel->lng,
                        'shopNum'       => $mapNationalStreetModel->shopNum,
                        'boundary'      => json_decode($mapNationalStreetModel->coords, true),
                        'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalStreetModel->grade] ?? '',
                        'label'         => [],
                        'head'          => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)optional($latestAudit)->openPotential] ?? '未评估',
                        'image'         => $auditCover,
                        'special'       => [
                            [
                                'name'  => '夸父门店数',
                                'value' => $mapNationalStreetModel->shopNum,
                            ]
                        ],
                        'openPotential' => (float)optional($latestAudit)->openPotential,
                        'province'      => $mapNationalStreetModel->province,
                        'city'          => $mapNationalStreetModel->city,
                        'district'      => $mapNationalStreetModel->district,
                    ];
                })->toArray();
                break;
            case 'communityData':
                $paginate = MapNationalCommunityModel::query()
                    ->where('city', 'like', mb_substr(str_replace('市', '', $city), 0, 2) . "%")
                    ->when($gradeWanggui, function ($query) use ($gradeWanggui) {
                        $param     = [];
                        $statusArr = explode(',', $gradeWanggui);
                        foreach ($statusArr as $item) {
                            $param[] = array_search($item, ProgrammingEnum::PC_GRADE_MAPPING);
                        }
                        $query->whereIn('grade', $param);
                    })
                    ->when($name, function ($query) use ($name) {
                        $query->where('address', 'like', "%{$name}%");
                    })
                    ->when(mb_strlen($setInType), function ($query) use ($setInType) {
                        $setInTypeArr = explode(',', $setInType);
                        if (count($setInTypeArr) != 2) {
                            if ($setInType == 0) {
                                $query->where('shopNum', 0);
                            } elseif ($setInType == 1) {
                                $query->where('shopNum', '>', 0);
                            }
                        }
                    })
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $list = $paginate->map(function (MapNationalCommunityModel $mapNationalCommunityModel) {
                    // 获得最新的评估记录
                    $latestAudit = null;
                    $auditCover  = optional($mapNationalCommunityModel->resourceWithMapRel)->url ? picturePath($mapNationalCommunityModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                    if (count($mapNationalCommunityModel->logRel)) {
                        $latestAudit = collect($mapNationalCommunityModel->logRel)->sortByDesc('updatedAt')->first();
                        if (count($latestAudit->resourceRelByCover)) {
                            foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                $auditCover = picturePath($resourceRelByCover->url);
                                break;
                            }
                        }
                    }
                    return [
                        'id'            => $mapNationalCommunityModel->id,
                        'name'          => $mapNationalCommunityModel->address,
                        'type'          => 'communityProgramming',
                        'lat'           => $mapNationalCommunityModel->lat,
                        'lng'           => $mapNationalCommunityModel->lng,
                        'shopNum'       => $mapNationalCommunityModel->shopNum,
                        'boundary'      => json_decode($mapNationalCommunityModel->coords, true),
                        'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalCommunityModel->grade] ?? '',
                        'label'         => [],
                        'head'          => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)optional($latestAudit)->openPotential] ?? '未评估',
                        'image'         => $auditCover,
                        'special'       => [
                            [
                                'name'  => '夸父门店数',
                                'value' => $mapNationalCommunityModel->shopNum,
                            ]
                        ],
                        'openPotential' => (float)optional($latestAudit)->openPotential,
                        'province'      => $mapNationalCommunityModel->province,
                        'city'          => $mapNationalCommunityModel->city,
                        'district'      => $mapNationalCommunityModel->district,
                    ];
                })->toArray();
                break;
            case 'nationalIndustrialParkData':
                $paginate = MapNationalIndustrialParkModel::query()
                    ->where('city', 'like', mb_substr(str_replace('市', '', $city), 0, 2) . "%")
                    ->when($gradeWanggui, function ($query) use ($gradeWanggui) {
                        $param     = [];
                        $statusArr = explode(',', $gradeWanggui);
                        foreach ($statusArr as $item) {
                            $param[] = array_search($item, ProgrammingEnum::PC_GRADE_MAPPING);
                        }
                        $query->whereIn('grade', $param);
                    })
                    ->when($name, function ($query) use ($name) {
                        $query->where('name', 'like', "%{$name}%");
                    })
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->when(mb_strlen($setInType), function ($query) use ($setInType) {
                        $setInTypeArr = explode(',', $setInType);
                        if (count($setInTypeArr) != 2) {
                            if ($setInType == 0) {
                                $query->where('shopNum', 0);
                            } elseif ($setInType == 1) {
                                $query->where('shopNum', '>', 0);
                            }
                        }
                    })
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $list = $paginate->map(function (MapNationalIndustrialParkModel $mapNationalIndustrialParkModel) {
                    //获得最新的评估记录
                    $latestAudit = null;
                    $auditCover  = optional($mapNationalIndustrialParkModel->resourceWithMapRel)->url ? picturePath($mapNationalIndustrialParkModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                    if (count($mapNationalIndustrialParkModel->logRel)) {
                        $latestAudit = collect($mapNationalIndustrialParkModel->logRel)->sortByDesc('updatedAt')->first();
                        if (count($latestAudit->resourceRelByCover)) {
                            foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                $auditCover = picturePath($resourceRelByCover->url);
                                break;
                            }
                        }
                    }

                    return [
                        'id'            => $mapNationalIndustrialParkModel->id,
                        'name'          => $mapNationalIndustrialParkModel->name,
                        'type'          => 'parkProgramming',
                        'lat'           => $mapNationalIndustrialParkModel->lat,
                        'lng'           => $mapNationalIndustrialParkModel->lon,
                        'shopNum'       => $mapNationalIndustrialParkModel->shopNum,
                        'boundary'      => [],
                        'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalIndustrialParkModel->grade] ?? '',
                        'label'         => [],
                        'head'          => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)optional($latestAudit)->openPotential] ?? '未评估',
                        'image'         => $auditCover,
                        'special'       => [
                            [
                                'name'  => '夸父门店数',
                                'value' => $mapNationalIndustrialParkModel->shopNum,
                            ]
                        ],
                        'openPotential' => (float)optional($latestAudit)->openPotential,
                        'province'      => $mapNationalIndustrialParkModel->province,
                        'city'          => $mapNationalIndustrialParkModel->city,
                        'district'      => $mapNationalIndustrialParkModel->district,
                    ];
                })->toArray();
                break;
            case 'townData':
                $paginate = MapTownshipPlanAreaModel::query()
                    ->where('city', 'like', mb_substr(str_replace('市', '', $city), 0, 2) . "%")
                    ->when($gradeWanggui, function ($query) use ($gradeWanggui) {
                        $param     = [];
                        $statusArr = explode(',', $gradeWanggui);
                        foreach ($statusArr as $item) {
                            $param[] = array_search($item, ProgrammingEnum::PC_GRADE_MAPPING);
                        }
                        $query->whereIn('grade', $param);
                    })
                    ->when($name, function ($query) use ($name) {
                        $query->where('area', 'like', "%{$name}%");
                    })
                    ->when(mb_strlen($setInType), function ($query) use ($setInType) {
                        $setInTypeArr = explode(',', $setInType);
                        if (count($setInTypeArr) != 2) {
                            if ($setInType == 0) {
                                $query->where('shopNum', 0);
                            } elseif ($setInType == 1) {
                                $query->where('shopNum', '>', 0);
                            }
                        }
                    })
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $list = $paginate->map(function (MapTownshipPlanAreaModel $mapTownshipPlanAreaModel) {

                    //获得最新的评估记录
                    $latestAudit = null;
                    $auditCover  = optional($mapTownshipPlanAreaModel->resourceWithMapRel)->url ? picturePath($mapTownshipPlanAreaModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                    if (count($mapTownshipPlanAreaModel->logRel)) {
                        $latestAudit = collect($mapTownshipPlanAreaModel->logRel)->sortByDesc('updatedAt')->first();
                        if (count($latestAudit->resourceRelByCover)) {
                            foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                $auditCover = picturePath($resourceRelByCover->url);
                                break;
                            }
                        }
                    }

                    return [
                        'id'            => $mapTownshipPlanAreaModel->id,
                        'name'          => $mapTownshipPlanAreaModel->area,
                        'type'          => 'townProgramming',
                        'lat'           => $mapTownshipPlanAreaModel->lat,
                        'lng'           => $mapTownshipPlanAreaModel->lng,
                        'shopNum'       => $mapTownshipPlanAreaModel->shopNum,
                        'boundary'      => [],
                        'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapTownshipPlanAreaModel->grade] ?? '',
                        'label'         => array_merge(
                            ($mapTownshipPlanAreaModel->shopCountRank ? ['商超数排名第' . $mapTownshipPlanAreaModel->shopCountRank] : []),
                            ($mapTownshipPlanAreaModel->qianqiangTownRank ? ['千强镇第' . $mapTownshipPlanAreaModel->qianqiangTownRank . '名'] : [])
                        ),
                        'head'          => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)optional($latestAudit)->openPotential] ?? '未评估',
                        'image'         => $auditCover,
                        'special'       => [
                            [
                                'name'  => '人口密度',
                                'value' => round($mapTownshipPlanAreaModel->peopleDensity, 1),
                            ], [
                                'name'  => '人口密度排名',
                                'value' => $mapTownshipPlanAreaModel->peopleDensityRank,
                            ], [
                                'name'  => '夸父门店数',
                                'value' => $mapTownshipPlanAreaModel->shopNum,
                            ]
                        ],
                        'openPotential' => (float)optional($latestAudit)->openPotential,
                        'province'      => $mapTownshipPlanAreaModel->province,
                        'city'          => $mapTownshipPlanAreaModel->city,
                        'district'      => $mapTownshipPlanAreaModel->district,
                    ];
                })->toArray();
                break;
            case 'nationalUniversitiesData':
                $paginate = MapNationalUniversitiesModel::query()
                    ->where('city', 'like', mb_substr(str_replace('市', '', $city), 0, 2) . "%")
                    ->when($gradeWanggui, function ($query) use ($gradeWanggui) {
                        $param     = [];
                        $statusArr = explode(',', $gradeWanggui);
                        foreach ($statusArr as $item) {
                            $param[] = array_search($item, ProgrammingEnum::PC_GRADE_MAPPING);
                        }
                        $query->whereIn('grade', $param);
                    })
                    ->when($name, function ($query) use ($name) {
                        $query->where('name', 'like', "%{$name}%");
                    })
                    ->when(mb_strlen($setInType), function ($query) use ($setInType) {
                        $setInTypeArr = explode(',', $setInType);
                        if (count($setInTypeArr) != 2) {
                            if ($setInType == 0) {
                                $query->where('shopNum', 0);
                            } elseif ($setInType == 1) {
                                $query->where('shopNum', '>', 0);
                            }
                        }
                    })
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $list = $paginate->map(function (MapNationalUniversitiesModel $mapNationalUniversitiesModel) {

                    //获得最新的评估记录
                    $latestAudit = null;
                    $auditCover  = optional($mapNationalUniversitiesModel->resourceWithMapRel)->url ? picturePath($mapNationalUniversitiesModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                    if (count($mapNationalUniversitiesModel->logRel)) {
                        $latestAudit = collect($mapNationalUniversitiesModel->logRel)->sortByDesc('updatedAt')->first();
                        if (count($latestAudit->resourceRelByCover)) {
                            foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                $auditCover = picturePath($resourceRelByCover->url);
                                break;
                            }
                        }
                    }

                    return [
                        'id'            => $mapNationalUniversitiesModel->id,
                        'name'          => $mapNationalUniversitiesModel->name,
                        'type'          => 'schoolProgramming',
                        'lat'           => $mapNationalUniversitiesModel->lat,
                        'lng'           => $mapNationalUniversitiesModel->lon,
                        'shopNum'       => $mapNationalUniversitiesModel->shopNum,
                        'boundary'      => [],
                        'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalUniversitiesModel->grade] ?? '',
                        'label'         => array_merge(
                            ($mapNationalUniversitiesModel->doubleFirstClass == '是' ? ['双一流'] : []),
                            ($mapNationalUniversitiesModel->project985 == '是' ? ['985'] : []),
                            ($mapNationalUniversitiesModel->project211 == '是' ? ['211'] : []),
                            ($mapNationalUniversitiesModel->strongBasis == '是' ? ['强基'] : [])
                        ),
                        'head'          => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)optional($latestAudit)->openPotential] ?? '未评估',
                        'image'         => $auditCover,
                        'special'       => [
                            [
                                'name'  => '院校类型',
                                'value' => $mapNationalUniversitiesModel->schoolType,
                            ], [
                                'name'  => '面积',
                                'value' => $mapNationalUniversitiesModel->space . '亩',
                            ], [
                                'name'  => '夸父门店数',
                                'value' => $mapNationalUniversitiesModel->shopNum,
                            ]
                        ],
                        'openPotential' => (float)optional($latestAudit)->openPotential,
                        'province'      => $mapNationalUniversitiesModel->province,
                        'city'          => $mapNationalUniversitiesModel->city,
                        'district'      => $mapNationalUniversitiesModel->district,
                    ];
                })->toArray();
                break;
            case 'competition':
                $paginate = MapNationalBrandShopModel::query()
                    ->where('city', 'like', mb_substr(str_replace('市', '', $city), 0, 2) . "%")
                    ->when($name, function ($query) use ($name) {
                        $query->where('name', 'like', "%{$name}%");
                    })
                    ->whereIn('brand', ProgrammingEnum::BRAND_SAND_TABLE_COMPETITIVE_PRODUCTS_MAPPING)
                    ->when(strlen($competition), function ($q) use ($competition) {
                        $competitionArr = explode(',', $competition);
                        $brand          = [];
                        foreach ($competitionArr as $item) {
                            $brand[] = array_search($item, ProgrammingEnum::BRAND_SHOP_MAPPING);
                        }
                        $q->whereIn('brand', $brand);
                    })
                    ->with([
                        'resourceWithMapRel',
                    ])
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $list = $paginate->map(function (MapNationalBrandShopModel $mapNationalBrandShopModel) {
                    return [
                        'id'       => $mapNationalBrandShopModel->id,
                        'name'     => $mapNationalBrandShopModel->name,
                        'brand'    => $mapNationalBrandShopModel->brand,
                        'type'     => 'product',
                        'lat'      => $mapNationalBrandShopModel->lat,
                        'lng'      => $mapNationalBrandShopModel->lon,
                        'boundary' => [],
                        'grade'    => '',
                        'label'    => [],
                        'head'     => '',
                        'image'    => (optional($mapNationalBrandShopModel->resourceWithMapRel)->url ? picturePath($mapNationalBrandShopModel->resourceWithMapRel->url) : '') ?: (ProgrammingEnum::BRAND_SHOP_LOG_IMAGE_MAPPING[$mapNationalBrandShopModel->brand] ?? SandTableEnum::DEFAULT_COVER_IMAGE_BASIC),
                        'special'  => [
                        ],
                        'province' => $mapNationalBrandShopModel->province,
                        'city'     => $mapNationalBrandShopModel->city,
                        'district' => $mapNationalBrandShopModel->district,
                    ];
                })->toArray();
                break;
            case 'complement':
                $paginate = MapNationalBrandShopModel::query()
                    ->where('city', $city)
                    ->when($name, function ($query) use ($name) {
                        $query->where('name', 'like', "%{$name}%");
                    })
                    ->whereIn('brand', ProgrammingEnum::BRAND_SAND_TABLE_COMPLEMENTARY_PRODUCTS_MAPPING)
                    ->when(strlen($complement), function ($q) use ($complement) {
                        $complementArr = explode(',', $complement);
                        $brand         = [];
                        foreach ($complementArr as $item) {
                            $brand[] = array_search($item, ProgrammingEnum::BRAND_SHOP_MAPPING);
                        }
                        $q->whereIn('brand', $brand);
                    })
                    ->with([
                        'resourceWithMapRel',
                    ])
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $list = $paginate->map(function (MapNationalBrandShopModel $mapNationalBrandShopModel) {
                    return [
                        'id'       => $mapNationalBrandShopModel->id,
                        'name'     => $mapNationalBrandShopModel->name,
                        'brand'    => $mapNationalBrandShopModel->brand,
                        'type'     => 'product',
                        'lat'      => $mapNationalBrandShopModel->lat,
                        'lng'      => $mapNationalBrandShopModel->lon,
                        'boundary' => [],
                        'grade'    => '',
                        'label'    => [],
                        'head'     => '',
                        'image'    => (optional($mapNationalBrandShopModel->resourceWithMapRel)->url ? picturePath($mapNationalBrandShopModel->resourceWithMapRel->url) : '') ?: (ProgrammingEnum::BRAND_SHOP_LOG_IMAGE_MAPPING[$mapNationalBrandShopModel->brand] ?? SandTableEnum::DEFAULT_COVER_IMAGE_BASIC),
                        'special'  => [
                        ],
                        'province' => $mapNationalBrandShopModel->province,
                        'city'     => $mapNationalBrandShopModel->city,
                        'district' => $mapNationalBrandShopModel->district,
                    ];
                })->toArray();
                break;
            default:
                throw new ResponseHttpException(404, null, '类型不存在');
        }

        return [
            'list'       => $list,
            'totalCount' => $paginate->total(),
            'totalPages' => $paginate->currentPage(),
            'pageNum'    => $pageNum,
            'pageSize'   => $pageSize
        ];

    }


    /**
     * 获取网规渗透率
     * @param string $city
     * @return array
     */
    public static function penetrationByCity(string $city): array
    {

        ini_set('memory_limit', '1024M');
        $city = str_replace('城区', '市', $city);
        // 城市点位缓存
        $cityPointInfo = Cache::remember('wanggui:cityPointInfo:' . $city, 3600 * 5, function () use ($city) {
            return self::cityPintByPc($city);
        });

        $shopOpen        = 0;
        $shopPause       = 0;
        $shopPreparatory = 0;
        $kfShopList      = [];
        $wangguiPoint    = [];
        $wanggui         = [];

        foreach ($cityPointInfo as $type => $cityPoint) {
            if (in_array($type, array_keys(ProgrammingEnum::PC_TYPE_LIST_HEAD_KF_CHILDREN_MAPPING))) {
                $kfShopList = array_merge($kfShopList, $cityPoint);
            }

            if ($type == ProgrammingEnum::PC_TYPE_LIST_HEAD_KF_CHILDREN_OPEN) {
                $shopOpen = count($cityPoint);
            }
            if ($type == ProgrammingEnum::PC_TYPE_LIST_HEAD_KF_CHILDREN_PREPARATORY) {
                $shopPreparatory = count($cityPoint);
            }

            if ($type == ProgrammingEnum::PC_TYPE_LIST_HEAD_KF_CHILDREN_PAUSE) {
                $shopPause = count($cityPoint);
            }

            if (in_array($type, [ProgrammingEnum::PC_TYPE_LIST_HEAD_MALL, ProgrammingEnum::PC_TYPE_LIST_HEAD_STREET, ProgrammingEnum::PC_TYPE_LIST_HEAD_COMMUNITY, ProgrammingEnum::PC_TYPE_LIST_HEAD_PARK, ProgrammingEnum::PC_TYPE_LIST_HEAD_UNIVERSITIES, ProgrammingEnum::PC_TYPE_LIST_HEAD_TOWN])) {
                $wangguiPoint = array_merge($wangguiPoint, $cityPoint);
            }

        }

        $calculatePenetration = static function (Collection $data, string $grade): string {
            $gradeData   = $data->where('grade', $grade);
            $numerator   = $gradeData->where('shopNum', '>', 0)->count();
            $denominator = $gradeData->count();

            return ($denominator !== 0) ? round($numerator / $denominator, 4) * 100 : 0;
        };

        $unsiteInCount = static function (Collection $data, string $grade): int {
            return $data->where('grade', $grade)->where('shopNum', 0)->count();
        };

        $categories = ['mallData', 'streetData'];
        $labels     = [
            'mallData'   => '商场',
            'streetData' => '街道',
        ];
        $grades     = ['S', 'A', 'B', 'C', 'D'];

        foreach ($categories as $category) {
            if (isset($cityPointInfo[$category]) && count($cityPointInfo[$category])) {
                $collectedData = collect($cityPointInfo[$category]);

                $data = [];
                foreach ($grades as $grade) {
                    $data[] = [
                        'title'         => $grade . '级',
                        'penetration'   => $calculatePenetration($collectedData, $grade),
                        'unSiteInCount' => $unsiteInCount($collectedData, $grade)
                    ];
                }

                $wanggui[] = [
                    'text' => $labels[$category],
                    'data' => $data,
                ];
            }
        }

        $totalWangguiPoints = count($wangguiPoint);
        $totalShopOpen      = $shopOpen + $shopPreparatory;
        $overplus           = 0;
        $penetration        = 0;
        // 获得缓存中的数据
        $pointStatistics = self::pointStatistics();

        foreach ($pointStatistics['cityData'] as $statistic) {
            if (in_array($city, array_keys($statistic))) {
                $overplus    = $statistic[$city]['remainingPointNum'] ?? 0;
                $penetration = $statistic[$city]['cityPenetrationRate'] ?? 0;
            }
        }

        // 门店列表
        $kfShopListCollect = collect($kfShopList);
        $dau = $kfShopListCollect->where('grade', '!=', '')->count();

        return [
            'kfShop'  => [
                'open'         => $shopOpen,
                'pause'        => $shopPause,
                'preparatory'  => $shopPreparatory,
                'overplus'     => $overplus,
                'penetration'  => (float)str_replace('%', '', $penetration),
                'dau'          => $dau,
                'goodCount'    => $goodCount = $kfShopListCollect->whereIn('grade', ['明星', '金牛'])->count(),
                'badCount'     => $badCount = $kfShopListCollect->where('grade', '瘦狗')->count(),
                'problemCount' => $problemCount = $kfShopListCollect->where('grade', '问题')->count(),
                'stCount'      => $stCount = $kfShopListCollect->where('grade', 'ST')->count(),
                'good'         => $dau != 0 ? round($goodCount / $dau * 100, 2) : 0,
                'bad'          => $dau != 0 ? round($badCount / $dau * 100, 2) : 0,
                'problem'      => $dau != 0 ? round($problemCount / $dau * 100, 2) : 0,
                'st'           => $dau != 0 ? round($stCount / $dau * 100, 2) : 0,
            ],
            'wanggui' => $wanggui,
        ];
    }

    public static function heatMap(string $city, int $sourceType): array
    {
        $provinceList = WangGuiCityByPower::getChinaDistrict();
        $provinceCode = '';
        $cityCode     = '';
        foreach ($provinceList as $province) {
            foreach ($province['districts'] as $citySelf) {
                if (str_replace('城区', '市', $citySelf['name']) == str_replace('城区', '市', $city)) {
                    $provinceCode = $province['adcode'];
                    $cityCode     = $citySelf['adcode'];
                }
            }
        }

        if (!$provinceCode || !$cityCode) {
            return [];
        }
        return ['fileUrl' => WaiMaiAnalysisBuildService::getCoordinateOssPath($provinceCode, $cityCode, $sourceType, true, true)];
    }

    /**
     * 根据每个市获得下面每个区的数据聚合
     * @param $city
     * @param $shopStatus
     * @param $shopType
     * @param $shopLevel
     * @param $shopArea
     * @param $netLevel
     * @param $netType
     * @param $competition
     * @param $complement
     * @param $setInType
     * @return array|mixed
     */
    public static function pointGatherByDistrict($city, $shopStatus, $shopType, $shopName, $shopLevel, $shopArea, $netLevel, $netType, $competition, $complement, $setInType, $actualIncome, $shopOpenStartDate, $shopOpenEndDate)
    {
        $provinceList = WangGuiCityByPower::getChinaDistrict();

        $districtArr = [];
        foreach ($provinceList as $provinceRegion) {
            foreach ($provinceRegion['districts'] as $cityRegion) {
                if (str_replace('城区', '市', $city) == str_replace('城区', '市', $cityRegion['name'])) {
                    $districtArr = $cityRegion['districts'];
                }
            }
        }

        // 获得点位数据
        $city = str_replace('城区', '市', $city);
        // 城市点位缓存
        $cityPointInfo = Cache::remember('wanggui:cityPointInfo:' . $city, 3600 * 5, function () use ($city) {
            return self::cityPintByPc($city);
        });


        foreach ($districtArr as $key => $district) {

            $districtPointInfo = [];
            foreach ($cityPointInfo as $k => $cityPoint) {
                $districtPointInfo[$k] = collect($cityPoint)->where('district', $district['name'])->values()->toArray();
            }
            $kfShop = [];
            if (strlen($shopStatus)) {
                foreach (explode(',', $shopStatus) as $status) {
                    $kfShop = array_merge($kfShop, ($districtPointInfo[$status] ?? []));
                }
            }
            $districtArr[$key]['kfShopCount'] = 0;

            $unAreaCollect           = collect($kfShop)
                ->when(mb_strlen($shopName), function ($q) use ($shopName) {
                    return $q->filter(function ($item) use ($shopName) {
                        return strpos($item['name'], $shopName) !== false;
                    });
                })->when(mb_strlen($shopType), function ($q) use ($shopType) {
                    return $q->whereIn('storeType', explode(',', $shopType));
                })->when(mb_strlen($shopLevel), function ($q) use ($shopLevel) {
                    return $q->whereIn('grade', explode(',', $shopLevel));
                })->when(strlen($shopOpenStartDate) && strlen($shopOpenEndDate), function ($q) use ($shopOpenStartDate, $shopOpenEndDate) {
                    return $q->whereBetween('openBusinessDate', [$shopOpenStartDate, $shopOpenEndDate]);
                });
            $tempActualIncomeCollect = $unAreaCollect;
            $unActualIncomeArr       = [];
            $tempAreaKfShopCount     = 0;
            if (strlen($shopArea)) {
                foreach (explode(',', $shopArea) as $areaInterval) {
                    $tempAreaKfShopCount += (clone $unAreaCollect)->whereBetween('area', explode('-', $areaInterval))->count();
                    $unActualIncomeArr   = array_merge((clone $tempActualIncomeCollect)->whereBetween('area', explode('-', $areaInterval))->toArray(), $unActualIncomeArr);
                }
            } else {
                $tempAreaKfShopCount = $unAreaCollect->count();
                $unActualIncomeArr   = $tempActualIncomeCollect->toArray();
            }

            $tempActualKfShopCount = 0;

            if (strlen($actualIncome)) {
                foreach (explode(',', $actualIncome) as $actualIncomeInterval) {
                    $tempActualKfShopCount += (clone collect($unActualIncomeArr))->whereBetween('actualIncome', explode('-', $actualIncomeInterval))->count();
                }
            } else {
                $districtArr[$key]['kfShopCount'] = $tempAreaKfShopCount;
            }

            $districtArr[$key]['kfShopCount'] += $tempActualKfShopCount;

            $wanggui = [];
            if (strlen($netType)) {
                foreach (explode(',', $netType) as $wangguiType) {
                    $wanggui = array_merge($wanggui, ($districtPointInfo[$wangguiType] ?? []));
                }
            }

            $districtArr[$key]['wanggui'] = collect($wanggui)
                ->when(strlen($netLevel), function ($q) use ($netLevel) {
                    return $q->whereIn('grade', explode(',', $netLevel));
                })->when(strlen($setInType), function ($q) use ($setInType) {
                    $setInTypeArr = explode(',', $setInType);
                    if (count($setInTypeArr) != 2) {
                        if ($setInType == 1) {
                            return $q->where('shopNum', '>', 0);
                        } else {
                            return $q->where('shopNum', 0);
                        }
                    } else {
                        return $q;
                    }
                })->count();

            $competitionCount = 0;
            $complementCount  = 0;

            if (strlen($competition)) {
                foreach (explode(',', $competition) as $competitionSelf) {
                    $competitionCount += count($districtPointInfo[$competitionSelf] ?? []);
                }
            }
            if (strlen($complement)) {
                foreach (explode(',', $complement) as $complementSelf) {
                    $complementCount += count($districtPointInfo[$complementSelf] ?? []);
                }
            }

            $districtArr[$key]['competition'] = $competitionCount;
            $districtArr[$key]['complement']  = $complementCount;
        }

        return $districtArr;
    }


    /**
     * 全国点位统计
     * @return array
     */
    public static function pointStatistics(): array
    {

        $data = Cache::remember('tiger:wanggui:pointStatistics', 86400 * 2, function () {
            ini_set('memory_limit', '1024M');

            // 获得全国行政区域
            $provinceList = WangGuiCityByPower::getChinaDistrict();

            GuanyuanDataService::setTimeOut(20);
            $dotPlan = GuanyuanDataService::dotPlan();

            $shopList = GuanyuanSyncShopListModel::query()
                ->get();

            // 选址中的单独处理
            $siteList = OpenShopSiteLocationModel::query()
                ->where('source', OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
                ->where('cityCode', '>', 0)
                ->whereNotIn('createdByUid', [139, 14])
                ->whereIn('siteStatus', [
                    OpenShopSiteLocationModel::SITE_STATUS_0,
                    OpenShopSiteLocationModel::SITE_STATUS_1,
                    OpenShopSiteLocationModel::SITE_STATUS_2,
                    OpenShopSiteLocationModel::SITE_STATUS_3,
                    OpenShopSiteLocationModel::SITE_STATUS_10,
                    OpenShopSiteLocationModel::SITE_STATUS_11,
                    OpenShopSiteLocationModel::SITE_STATUS_20,
                ])
                ->get()
                ->map(function (OpenShopSiteLocationModel $openShopSiteLocationModel) {
                    $regionArr = explode('-', $openShopSiteLocationModel->cityArea);
                    if (count($regionArr) < 2) {
                        return null;
                    }

                    return [
                        'province' => $regionArr[0],
                        'city'     => $regionArr[1],
                    ];
                })->filter()->values();

            $data = [
                'cityData'     => [],
                'provinceData' => [],
                'total'        => [
                    'businessShopTotalNum'   => (clone $shopList)->where('province', '!=', '')->whereIn('status', ['正常营业', '暂停营业'])->count(),
                    'prepareShopTotalNum'    => (clone $shopList)->where('province', '!=', '')->where('status', '筹备中')->count(),
                    'siteShopTotalNum'       => (clone $siteList)->count(),
                    'remainingPointTotalNum' => (int)collect($dotPlan)->sum('剩余点位_正常版'),
                ]
            ];

            foreach ($provinceList as $province) {

                $siteProvinceNum = (clone $siteList)->where('province', $province['name'])->count();

                // 聚合省的信息
                $data['provinceData'][$province['name']] = [
                    'province'            => $province['name'],
                    'adcode'              => $province['adcode'],
                    'lng'                 => explode(',', $province['center'])[0],
                    'lat'                 => explode(',', $province['center'])[1],
                    'capacity'            => (int)collect($dotPlan)->where('省', $province['name'])->sum('正常版网规'),
                    'cityPenetrationRate' => (int)collect($dotPlan)->where('省', $province['name'])->sum('正常版网规') ? (round((int)collect($dotPlan)->where('省', $province['name'])->sum('当前门店数') / (int)collect($dotPlan)->where('省', $province['name'])->sum('正常版网规'), 4) * 100 . '%') : '0%',
                    'shopNum'             => (clone $shopList)->where('province', $province['name'])->whereIn('status', ['正常营业', '暂停营业', '筹备中'])->count() + $siteProvinceNum,
                    'businessShopNum'     => (clone $shopList)->where('province', $province['name'])->whereIn('status', ['正常营业', '暂停营业'])->count(),
                    'siteShopNum'         => $siteProvinceNum,
                    'prepareShopNum'      => (clone $shopList)->where('province', $province['name'])->where('status', '筹备中')->count(),
                    'remainingPointNum'   => (int)collect($dotPlan)->where('省', $province['name'])->sum('剩余点位_正常版'),
                ];

                foreach ($province['districts'] as $city) {
                    $cityName = str_replace('城区', '市', $city['name']);

                    $siteCityNum = (clone $siteList)->where('province', $province['name'])->where('city', $cityName)->count();

                    // 聚合市的信息
                    $data['cityData'][$province['name']][$cityName] = [
                        'city'                => $cityName,
                        'adcode'              => $city['adcode'],
                        'lng'                 => explode(',', $city['center'])[0],
                        'lat'                 => explode(',', $city['center'])[1],
                        'capacity'            => (int)collect($dotPlan)->where('省', $province['name'])->where('市', $cityName)->sum('正常版网规'),
                        'cityPenetrationRate' => (int)collect($dotPlan)->where('省', $province['name'])->where('市', $cityName)->sum('正常版网规') ? (round((int)collect($dotPlan)->where('省', $province['name'])->where('市', $cityName)->sum('当前门店数') / (int)collect($dotPlan)->where('省', $province['name'])->where('市', $cityName)->sum('正常版网规'), 4) * 100 . '%') : '0%',
                        'shopNum'             => (clone $shopList)->where('province', $province['name'])->where('city', $cityName)->whereIn('status', ['正常营业', '暂停营业', '筹备中'])->count() + $siteCityNum,
                        'businessShopNum'     => (clone $shopList)->where('province', $province['name'])->where('city', $cityName)->whereIn('status', ['正常营业', '暂停营业'])->count(),
                        'siteShopNum'         => $siteCityNum,
                        'prepareShopNum'      => (clone $shopList)->where('province', $province['name'])->where('city', $cityName)->where('status', '筹备中')->count(),
                        'remainingPointNum'   => (int)collect($dotPlan)->where('省', $province['name'])->where('市', $cityName)->sum('剩余点位_正常版'),
                    ];
                }
            }
            return $data;
        });

        return $data;
    }


    /**
     * 获得营业趋势
     * @param $shopCode
     * @return array|mixed
     */
    public static function businessTrend($shopCode)
    {
        try {
            $shopId         = (int)optional(optional(OpenShopSignOrderModel::query()->where('shopCode', $shopCode)->where('status', '!=', SignOrderEnum::ORDER_STATUS_NO)->with(['mainProcessRel'])->first())->mainProcessRel)->shopId;
            $showTimeTab    = 5;
            $showStartAt    = Carbon::now()->subDays(30)->startOfDay()->timestamp;
            $showEndAt      = Carbon::today()->startOfDay()->timestamp;
            $compareTimeTab = 4;
            $compareStartAt = Carbon::now()->subDays(60)->startOfDay()->timestamp;
            $compareEndAt   = Carbon::now()->subDays(30)->startOfDay()->timestamp;
            //获取折线图
            $res = (new RmsShopApi())->indexCharts($shopId, $showTimeTab, $showStartAt, $showEndAt, $compareTimeTab, $compareStartAt, $compareEndAt);
            if ($res['code'] == 1) {
                $charts = $res['data'];
            } else {
                $charts = [];
            }
        } catch (\Exception $exception) {
            $charts = [];
        }

        return $charts;
    }


    /**
     * 根据门店编号获得优先级的图片
     * @param array $shopCodes
     * @param array $orderNoWithCode 订单号与code的关联关系  key=code value=orderNo
     * @return array
     */
    public static function getShopImageByShopCode(array $shopCodes = [], array $orderNoWithCode = []): array
    {

        if (empty($shopCodes) && empty($orderNoWithCode)) {
            return [];
        }

        if (empty($shopCodes)) {
            $codes = array_keys($orderNoWithCode);
        } else {
            $codes = $shopCodes;
        }

        $defaultImage = [];

        // 获得默认图片
        $wgNumberArr = [];
        collect($codes)->each(function ($code) use (&$wgNumberArr) {
            $wgNumberArr[$code] = 'KFZC' . str_pad($code, 7, '0', STR_PAD_LEFT);
        })->toArray();

        ResourcesModel::query()
            ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
            ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
            ->where('businessId', 0)
            ->whereIn('name', array_values($wgNumberArr))
            ->select(['url', 'name'])
            ->get()
            ->each(function (ResourcesModel $resourcesModel) use (&$defaultImage, $wgNumberArr) {
                $code = array_search($resourcesModel->name, $wgNumberArr);
                if ($code != 0) {
                    $defaultImage[$code] = picturePath($resourcesModel->url);
                }
            });

        // 根据shopCode获得orderNos
        if (empty($orderNoWithCode)) {
            $orderNos = GuanyuanSyncShopListModel::query()->whereIn('code', $shopCodes)->pluck('orderNo', 'code')->toArray();
        } else {
            $orderNos = $orderNoWithCode;
        }

        // 筹备的图片
        OpenShopUploadFileResourceModel::query()
            ->whereIn('orderNo', array_values(array_unique($orderNos)))
            ->where('businessId', 0)
            ->where('position', 25)
            ->where('type', OpenShopUploadFileResourceModel::FILE_TYPE_IMG)
            ->get()
            ->each(function (OpenShopUploadFileResourceModel $openShopUploadFileResourceModel) use (&$defaultImage, $orderNos) {
                $code = array_search($openShopUploadFileResourceModel->orderNo, $orderNos);
                if ($code !== false) {
                    $defaultImage[$code] = $openShopUploadFileResourceModel->formatUrl;
                }
            });


        // 开业报告的图片
        CruiseOrderModel::query()
            ->whereIn('orderNo', array_values(array_unique($orderNos)))
            ->where('type', CruiseOrderModel::TYPE_NEW_SHOP_HELP)
            ->with(['openReportFileRel'])
            ->get()
            ->each(function (CruiseOrderModel $cruiseOrderModel) use (&$defaultImage, $orderNos) {
                $code = array_search($cruiseOrderModel->orderNo, $orderNos);
                if ($cruiseOrderModel->openReportFileRel != null && $code !== false) {
                    $defaultImage[$code] = picturePath($cruiseOrderModel->openReportFileRel->url);
                }
            });

        return $defaultImage;
    }


}
